<?php


namespace wx;


class Wxapp
{
    protected $data = array('flag' => 0, 'msg' => '', 'data' => '');
    public function getUser_info($code = '')
    {
        if (empty($code)) {
            $this->data['flag'] = 0;
            $this->data['msg'] = '授权失败！';
        } else {
            // 获取页面URL的CODE参数，判断是否有值
            // 获取openid和access_token
            $app_id = "wx052987ea2208ce0c";
            $app_secret = 'cc552aad9a79685fccc21fdb778202f0';
            // 发送请求，获取用户openid和access_token
            $data = $this->get_by_curl('https://api.weixin.qq.com/sns/jscode2session?appid='.$app_id.'&secret='.$app_secret.'&js_code='.$code.'&grant_type=authorization_code');
            $data = json_decode($data);

            // 防止第二次访问动态链接报错
            // 判断是否获取到当前用户的openid
            if (isset($data->openid)) {
                $open_id = $data->openid;
                $this->data['data']=['openid'=>$open_id];
                $this->data['flag']=1;
                $this->data['msg']='获取成功';
                return  $this->data;
            }
            $this->data['msg']='获取信息失败';
            return $this->data;
        }
    }


    // 用于请求微信接口获取数据
    function get_by_curl($url, $post = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($post) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}